var dataChecker = require('./util/dataChecker.js');
var myUtil = require('./util/myUtil.js');
var util = require('util');
var EventEmitter = require('events').EventEmitter;

function ClientItemUnAuth(socket) {
	this.socket = socket;
	this.timer = null;
}
util.inherits(ClientItemUnAuth, EventEmitter);

// request auth, and wait auth in 5 seconds
ClientItemUnAuth.prototype.start = function() {
	console.log("start");
	var that = this;
	that.socket.write("require send info");
	that.timer = setTimeout(function() {
		console.log("auth_timeout");
		that.emit("auth_timeout");
	}, 5000);

	that.socket.on('data', function(chunk) {
		var json = parseInput(chunk);
		if (!json.data) {
			return;
		}

		checkToken(json.data.token, function(isOk, msg) {
			if (isOk) {
				console.log("auth_done");
				clearTimeout(that.timer);
				that.socket.removeAllListeners('data');
				that.emit("auth_done", json.data.deviceUuid);
			} else {
				// continue wait until timeout
			}
		});
	});
}

//
var template = {
	token: "xxx",
	deviceUuid: "xxx"
}

function parseInput(data) {
	console.log("parseInput:" + data);
	var json = myUtil.str2Json(data);
	if (!json) {
		return myUtil.resJsonErr("canot parse to json");
	}

	var checkResult = dataChecker.check(template, json);
	if (checkResult.isOk === false) {
		return myUtil.resJsonErr(checkResult.msg);
	}

	return myUtil.resJsonOk(json);
}

// TODO check token
function checkToken(token, callback) {
	callback(true, null);
}

ClientItemUnAuth.prototype.finish = function() {
	// TODO
	console.log("finish unauth socket");
	this.socket.end();
	this.socket = null;
	if (this.timer) {
		clearTimeout(this.timer);
		this.timer = null;
	}
}


module.exports = ClientItemUnAuth;